package com.zpark.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.zpark.pojo.Dept;
import com.zpark.service.IDeptService;
import com.zpark.utils.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @PackageName: com.zpark.controller
 * @ClassName: DeptController
 * @Description:
 * @author: RZS
 * @date: 2024/5/7  10:51
 */
@RestController
public class DeptController {

    @Autowired
    private IDeptService deptService;

    @GetMapping("/by_id/{id}")
    @SentinelResource(value = "findById",
    fallback = "findByIdHandler")
    public ResponseData<Dept> findById(@PathVariable Integer id){
        try {
            // 模拟请求接口响应缓慢，阻塞2秒
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new ResponseData<>(2000, "SUCCESS", deptService.findById(id));
    }

    @GetMapping("/all")
    public ResponseData<List<Dept>> findAll(){
        return new ResponseData<>(2000, "SUCCESS", deptService.findAll());
    }

    // 服务降级处理方法的异常必须为Throwable，否则页码展示500错误
    public ResponseData<Dept> findByIdHandler(@PathVariable Integer id, Throwable e){
        return new ResponseData<>(5000, "Error", null);
    }
}
